/**
* @Description: 商品价格查询(客户使用)
* @author  tangbin
* @date 2023/3/10
*/
<template>
  <div class="app-containers">
    <query-table-render
        ref="queryTable"
        :query-model="queryModel"
        :table-request="requestTableData"
        :table-column="tableColumns"
        :toolbar-render="toolbarRnd"
        :transform-query="transformQuery"
        :title-render="titleRender"
        @on-operator="onOperator"
        :show-table-batch-view="showTableBatchView"
    >
      <template v-slot:form>
        <el-form-item label="商品编码" prop="goodsCode">
          <el-input v-model="queryModel.goodsCode" placeholder="请输入" clearable @keyup.enter.native="searchListQuery"/>
        </el-form-item>
        <el-form-item label="商品名称" prop="goodsName">
          <el-input v-model="queryModel.goodsName" placeholder="请输入" clearable @keyup.enter.native="searchListQuery"/>
        </el-form-item>
        <!-- <el-form-item label="供方编码" prop="supplierCode">
          <el-input v-model="queryModel.supplierCode" placeholder="请输入" clearable @keyup.enter.native="searchListQuery"/>
        </el-form-item> -->
        <!-- <el-form-item label="销售区域" prop="salesArea">
          <el-cascader
            size="small"
            style="width:100%"
            v-model="queryModel.salesArea"
            :options="areaList"
            :props="propsArea"
            clearable
          />
        </el-form-item> -->
        <el-form-item label="价目表名称" prop="priceId">
          <el-select v-model="queryModel.priceId" placeholder="请选择" style="width:100%" clearable filterable>
            <el-option
              v-for="item in pricesList"
              :key="item.id"
              :label="item.priceAlias"
              :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="商品分类" prop="goodsClassId">
          <el-select v-model="queryModel.goodsClassId" placeholder="请选择" style="width:100%" clearable>
            <el-option
              v-for="item in goodsClassList"
              :key="item.id"
              :label="item.name"
              :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="商品状态" prop="goodsStatus">
          <el-select v-model="queryModel.goodsStatus" placeholder="请选择" style="width:100%" clearable>
            <el-option
                v-for="item in dict.type.basic_data_goods_status"
                :key="item.value"
                :label="item.label"
                :value="item.value"/>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="价格状态" prop="priceGoodsStatus">
          <el-select v-model="queryModel.priceGoodsStatus" placeholder="请选择" style="width:100%" clearable>
            <el-option
                v-for="item in dict.type.price_goods_status"
                :key="item.value"
                :label="item.label"
                :value="item.value"/>
          </el-select>
        </el-form-item> -->
        <!-- <el-form-item label="订单类型" prop="orderType">
          <el-select v-model="queryModel.orderType" placeholder="请选择" style="width:100%" clearable>
            <el-option
                v-for="item in dict.type.order_type"
                :key="item.value"
                :label="item.label"
                :value="item.value"/>
          </el-select>
        </el-form-item> -->
        <!-- <el-form-item label="价目生效日期" prop="priceEffectiveDateRange" :autoAlign="true">
          <el-date-picker
              v-model="queryModel.priceEffectiveDateRange"
              type="daterange"
              format="yyyy/MM/dd"
              value-format="yyyy-MM-dd"
              range-separator="-"
              style="width:100%"
              start-placeholder="开始时间"
              end-placeholder="结束时间">
          </el-date-picker>
        </el-form-item> -->
        <!-- <el-form-item label="价目失效日期" prop="priceExpireDateRange" :autoAlign="true">
          <el-date-picker
              v-model="queryModel.priceExpireDateRange"
              type="daterange"
              format="yyyy/MM/dd"
              range-separator="-"
              style="width:100%"
              value-format="yyyy-MM-dd"
              start-placeholder="开始时间"
              end-placeholder="结束时间">
          </el-date-picker>
        </el-form-item> -->

      </template>
    </query-table-render>
  </div>
</template>


<script>
import {checkPermi} from '@/utils/permission.js'
import QueryTableRender from "@/components/QueryTableRender";
import {customerGoodsPrices} from '@/api/basic/goodsPriceCust.js'
import {listGoodsClassSelect} from '@/api/basic/commodity.js'
import {getDivisionTree} from '@/api/basic/orderGoodsClas.js'
import {settingPrices, priceListCustomerHelper} from '@/api/basic/sellPrices.js'
import dayjs from "dayjs"

export default {
  name: "GoodsPrices",
  dicts: ['basic_data_division', 'order_type', 'price_customer_mode', 'price_use_status', 'basic_data_customer_type', 'price_goods_status', 'basic_data_goods_status', 'basic_data_goods_type'], // 可配置价目表
  components: {QueryTableRender},

  data() {
    return {
      queryModel: {}, // 查询参数
      tableColumns: [], // 列表
      areaList:[], // 省市区
      propsArea: {label: 'name', value: 'id', children: 'children', checkStrictly: true},
      pricesList: [], // 价目表列表
      goodsClassList: [], // 商品分类
      showTableBatchView: false, // 是否显示批量视图
    }
  },
  created() {
    this.setupQueryModel();
    this.setupTableColumns();
  },
  mounted() {
    this.getDivisionTree();
    this.getSettingPrices();
    this.getListGoodsClassSelect(); // 商品分类
  },
  watch: {
    $route(route) {
      // console.log('name', route.name);
      if (route.name == 'GoodsPrices') {
        this.onRefreshTable();
      }
    },
  },
  methods: {
    /**
     * 初始化查询参数
     */
     setupQueryModel() {
      this.queryModel = {
        goodsCode: undefined, // 商品编码
        goodsName: undefined, // 商品名称
        priceId: undefined, // 价目表名称
        goodsClassId: undefined, // 商品分类
        goodsStatus: undefined, // 商品状态
        // priceGoodsStatus: undefined, // 价格状态

        // supplierCode: undefined, // 供方编码
        // salesArea: undefined, // 销售区域
        // salesAreaProvince: undefined, // 销售地区-省
        // salesAreaCity: undefined, // 销售地区-市
        // salesAreaDistrict: undefined, // 销售地区-区
        // orderType: undefined, // 订单类型
        // priceEffectiveDateRange: undefined, // 价目生效日期 [start, end]
        // priceEffectiveDateBegin: undefined, // 价目生效日期开始
        // priceEffectiveDateEnd: undefined, // 价目生效日期结束
        // priceExpireDateRange: undefined, //  价目生效日期 [start, end]
        // priceExpireDateBegin: undefined, // 价目失效日期开始
        // priceExpireDateEnd: undefined, // 价目失效日期结束

      };
    },

    setupTableColumns() {
      this.tableColumns = [
        {
          width: '60',
          type: 'selection',
          align: 'center',
        },
        {
          label: '序号',
          width: '60',
          type: 'index',
          increment: true
        },
        {
          prop: 'code',
          label: '商品编码',
          minWidth: '120',
        },
        {
          prop: 'goodsName',
          label: '商品名称',
          minWidth: '360',
          // showOverflowTooltip: true
        },
        {
          prop: 'ratePrice',
          label: '含税单价',
          align: 'right',
          minWidth: '120',
          render: (h, text) => {
            if (text) {
              return Number(text).toFixed(2);
            }
            return '';
          }
        },
        {
          prop: 'goodsReferencedNumber',
          label: '参图号',
          minWidth: '120'
        },
        {
          prop: 'priceAlias',
          label: '价目表名称',
          minWidth: '220',
          showOverflowTooltip: true
        },
        {
          prop: 'goodsClassName',
          label: '商品分类',
          minWidth: '220',
          showOverflowTooltip: true
        },
        {
          prop: 'goodsCategory',
          label: '商品类别',
          minWidth: '120',
          render: (h, text) => {
            let show = "";
            this.dict.type.basic_data_goods_type.some((item) => {
              if (item.value === text) {
                show = item.label;
                return true;
              }
            });
            return show;
          }
        },
        {
          prop: 'goodsStatus',
          label: '商品状态',
          minWidth: '120',
          render: (h, text) => {
            let show = "";
            this.dict.type.basic_data_goods_status.some((item) => {
              if (item.value === text) {
                show = item.label;
                return true;
              }
            });
            return show;
          }
        },
        // {
        //   prop: 'status',
        //   label: '价格状态',
        //   minWidth: '120',
        //   render: (h, text) => {
        //     let show = "";
        //     this.dict.type.price_goods_status.some((item) => {
        //       if (item.value === text) {
        //         show = item.label;
        //         return true;
        //       }
        //     });
        //     return show;
        //   }
        // },
        // {
        //   prop: 'salesArea',
        //   label: '销售区域',
        //   minWidth: '160',
        //   showOverflowTooltip: true
        // },
        { // 销售区域实际显示的是 包含行政区划的内容
          prop: 'divisionInfo',
          label: '销售区域',
          minWidth: '180',
          render:(h, text, {record}) => {
            let list = [];
            record.divisionInfo && record.divisionInfo.forEach((name) => {
              list.push(h('li', {style:'height: 22px; line-height: 22px; font-size: 14px; font-weight: 400;'}, name));
            });
            return h('el-tooltip', {props: {placement: 'top'}}, [
              h('div', {slot: 'content', style: 'min-width: 160px; max-height:236px; overflow: auto;'}, [
                h('ul', {style: 'list-style-type: none; padding-left:0;'}, list)
              ]),
              h('span', {style: 'overflow: hidden; text-overflow: ellipsis; white-space: nowrap;'}, record.divisionInfo && (record.divisionInfo.toString()).slice(0, 15))
            ]);
          }
        },
        // {
        //   prop: 'effectiveDate',
        //   label: '价格生效日期',
        //   minWidth: '120',
        //   render: (h, text) => {
        //     if (!text) return ''
        //     const dayjsData = dayjs(text)
        //     if (dayjsData.isValid() && dayjsData.isAfter(dayjs('1900'), 'year')) {
        //       return dayjsData.format('YYYY-MM-DD')
        //     }
        //     return text
        //   }
        // },
        // {
        //   prop: 'expireDate',
        //   label: '价格失效日期',
        //   minWidth: '120',
        //   render: (h, text) => {
        //     if (!text) return ''
        //     const dayjsData = dayjs(text)
        //     if (dayjsData.isValid() && dayjsData.isAfter(dayjs('1900'), 'year')) {
        //       return dayjsData.format('YYYY-MM-DD')
        //     }
        //     return text
        //   }
        // },
        {
          prop: 'supplierCode',
          label: '供方编码',
          minWidth: '160',
        },
        {
          prop: 'rate',
          label: '税率',
          minWidth: '100',
          align: 'right',
          render: (h, text) => {
            return text+'%';
          }
        },
        
        // {
        //   prop: 'divisionInfo',
        //   label: '包含行政区划',
        //   minWidth: '180',
        //   render:(h, text, {record}) => {
        //     let list = [];
        //     record.divisionInfo && record.divisionInfo.forEach((name) => {
        //       list.push(h('li', {style:'height: 22px; line-height: 22px; font-size: 14px; font-weight: 400;'}, name));
        //     });
        //     return h('el-tooltip', {props: {placement: 'top'}}, [
        //       h('div', {slot: 'content', style: 'min-width: 160px; max-height:236px; overflow: auto;'}, [
        //         h('ul', {style: 'list-style-type: none; padding-left:0;'}, list)
        //       ]),
        //       h('span', {style: 'overflow: hidden; text-overflow: ellipsis; white-space: nowrap;'}, record.divisionInfo && (record.divisionInfo.toString()).slice(0, 15))
        //     ]);
        //   }
        // },
        // {
        //   prop: 'sellerName',
        //   label: '销售组织',
        //   minWidth: '180',
        //   showOverflowTooltip: true
        // },
        
        // {
        //   prop: 'priceOrderType',
        //   label: '订单类型',
        //   align:'left',
        //   minWidth: '120',
        //   render: (h, text) => {
        //     let show = "";
        //     this.dict.type.order_type.some((item) => {
        //       if (item.value === text) {
        //         show = item.label;
        //         return true;
        //       }
        //     });
        //     return show;
        //   }
        // },
        {
          prop: 'effectiveDate',
          label: '价格生效日期',
          minWidth: '120',
          render: (h, text) => {
            if (!text) return ''
            const dayjsData = dayjs(text)
            if (dayjsData.isValid() && dayjsData.isAfter(dayjs('1900'), 'year')) {
              return dayjsData.format('YYYY-MM-DD')
            }
            return text
          }
        },
        {
          prop: 'expireDate',
          label: '价格失效日期',
          minWidth: '120',
          render: (h, text) => {
            if (!text) return ''
            const dayjsData = dayjs(text)
            if (dayjsData.isValid() && dayjsData.isAfter(dayjs('1900'), 'year')) {
              return dayjsData.format('YYYY-MM-DD')
            }
            return text
          }
        },
        // {
        //   prop: 'priceEffectiveDate',
        //   label: '价目生效日期',
        //   align:'left',
        //   minWidth: '140',
        //   render: (h, text) => {
        //     if (!text) return ''
        //     const dayjsData = dayjs(text)
        //     if (dayjsData.isValid() && dayjsData.isAfter(dayjs('1900'), 'year')) {
        //       return dayjsData.format('YYYY-MM-DD')
        //     }
        //     return text
        //   }
        // },
        // {
        //   prop: 'priceExpireDate',
        //   label: '价目失效日期',
        //   align:'left',
        //   minWidth: '140',
        //   render: (h, text) => {
        //     if (!text) return ''
        //     const dayjsData = dayjs(text)
        //     if (dayjsData.isValid() && dayjsData.isAfter(dayjs('1900'), 'year')) {
        //       return dayjsData.format('YYYY-MM-DD'); // format('YYYY-MM-DD HH:mm:ss')
        //     }
        //     return text
        //   }
        // },

      ];
    },

    /**
     * 查询列表
     * @param {*} queryParams
     */
     requestTableData(queryParams) {
      queryParams.effectiveDateBegin = undefined;
      queryParams.effectiveDateEnd = undefined;
      queryParams.expireDateBegin = undefined;
      queryParams.expireDateEnd = undefined;
      // console.log('effectiveTimeRange=', queryParams.priceEffectiveDateRange);
      if (queryParams.priceEffectiveDateRange && queryParams.priceEffectiveDateRange.length == 2) {
        queryParams.priceEffectiveDateBegin = queryParams.priceEffectiveDateRange[0];
        queryParams.priceEffectiveDateEnd = queryParams.priceEffectiveDateRange[1];
      }
      if (queryParams.priceExpireDateRange && queryParams.priceExpireDateRange.length == 2) {
        queryParams.priceExpireDateBegin = queryParams.priceExpireDateRange[0];
        queryParams.priceExpireDateEnd = queryParams.priceExpireDateRange[1];
      }
      if (queryParams.salesArea && queryParams.salesArea.length > 0) {
        if (queryParams.salesArea.length == 1) {
          queryParams.salesAreaProvince = queryParams.salesArea[0];
        } else if (queryParams.salesArea.length == 2) {
          queryParams.salesAreaProvince = queryParams.salesArea[0];
          queryParams.salesAreaCity = queryParams.salesArea[1];
        } else if (queryParams.salesArea.length == 3) {
          queryParams.salesAreaProvince = queryParams.salesArea[0];
          queryParams.salesAreaCity = queryParams.salesArea[1];
          queryParams.salesAreaDistrict = queryParams.salesArea[2];
        }
      }
      // console.log('查询queryParams=', queryParams);
      return customerGoodsPrices(queryParams).then(respData => {
        // console.log('respData=', respData);

        // divisionInfo 包含行政区划

        return {
          success: true,
          total: respData.data.total,
          data: respData.data.records,
        }
      });
    },

    /**
     * 刷新列表
     */
    onRefreshTable(){
      this.$refs['queryTable'].refreshTable()
    },

    toolbarRnd(h){
      let list = [];
      if (checkPermi(['basic-data:goods-price-customer:export'])) {
        list.push(<el-button type="primary" icon="el-icon-download" vOn:click={() => this.onExport()}>导出</el-button>);
      }
      return list;
    },

    transformQuery(queryData) {
      let transParams = {}
      for (let keyName in queryData) {
        if (queryData.hasOwnProperty(keyName)) {
          // if (keyName === 'createTimeRange') {
          //   if(queryData['createTimeRange'] && queryData['createTimeRange'].length){
          //     const [start, end] =  queryData[keyName]
          //     transParams['startTime'] = dayjs(start).startOf('day').format("YYYY-MM-DD HH:mm:ss")
          //     transParams['endTime'] = dayjs(end).endOf('day').format("YYYY-MM-DD HH:mm:ss")
          //   }
          // } else {
            transParams[keyName] = queryData[keyName]
          // }
        }
      }
      return transParams
    },

    titleRender(h) {
      return <div>
        <span style="display:inline-block; background-color: #1890FF;margin-bottom: -2px; margin-right: 8px; width: 3px; height: 14px"></span>
        <span style="display: inline-block; color: #333333; font-size: 16px;">商品价格</span>
      </div>;
    },

    /**
     * 搜索列表查询
     */
     searchListQuery() {
      this.$refs['queryTable'].submitQuery();
    },

    /**
     * 操作页面
     * @param {*} command
     * @param {*} record
     */
     onOperator(command, record) {

    },

    /**
     * 获取商品分类列表
     */
    getListGoodsClassSelect() {
      listGoodsClassSelect().then(res => {
        // console.log('商品分类列表=', res);
        if (res.code == 200) {
          this.goodsClassList = res.data;
        }
      }).catch(err => {

      });
    },

    /**
     * 获取行政区划数据
     */
     getDivisionTree() {
      getDivisionTree({name: ''}).then(res => {
        // console.log('res=', res);
        if (res.code === 200) {
          const list = res.data;
          if (list && list.length > 0) {
            this.areaList = list[0].children;
            // console.log('children=', list[0].children);
            // this.menuOptions = list[0].children;
          }
        }
      }).catch(err => {

      });
    },

    /**
     * 获取价目表列表
     */
    getSettingPrices() {
      priceListCustomerHelper({}).then(res => {
        console.log('res=', res);
        if (res.code == 200) {
          this.pricesList = res.data;
        }
      });
    },

    /**
     * 导出
     */
    onExport() {
      
      const selectedList = this.$refs['queryTable'].getSelection();
      let list = [];
      if (selectedList && selectedList.length > 0) {
        list = selectedList.map(item => {
          return item.id
        });
      }

      let param = {};
      if (list.length > 0) { // 选中的记录
        param = {exportIds: list};
      } else { // 未选中记录
        param = JSON.parse(JSON.stringify(this.queryModel));
        if (param.salesArea && param.salesArea.length > 0) {
          if (param.salesArea.length == 1) {
            param.salesAreaProvince = param.salesArea[0];
          } else if (param.salesArea.length == 2) {
            param.salesAreaProvince = param.salesArea[0];
            param.salesAreaCity = param.salesArea[1];
          } else if (param.salesArea.length == 3) {
            param.salesAreaProvince = param.salesArea[0];
            param.salesAreaCity = param.salesArea[1];
            param.salesAreaDistrict = param.salesArea[2];
          }
        }
        delete param.pageNum;
        delete param.pageSize;
      }
      
      let date = this.$moment(new Date()).format("YYYY-MM-DD");
      this.download('/basic/data/price/goods/export/customer', param, `商品价格_${date}.xlsx`)
    },

  },
}

</script>
